import React, { useEffect } from 'react'
import { Form, Input, Modal, Select } from "antd";

const { Option } = Select

const layout = {
  labelCol: {span: 5},
  wrapperCol: {span: 14},
};

export type addOrUpdateProps = {
  roles: object,
  visible: boolean,
  handleModalVisible?: any,
  allFields: any,
  onFieldsDataChange: any,
  addOrUpdateUser: any,
  setForm: any,
};

const AddUpdateForm: React.FC<addOrUpdateProps> = (props) => {
  const [form] = Form.useForm();
  const {
    handleModalVisible,
    visible,
    roles,
    allFields,
    onFieldsDataChange,
    addOrUpdateUser,
    setForm,
  } = props

  const onFieldsChange = (changedFields: any, date: object) => {
    onFieldsDataChange(date)
  }

  const modalOk = () => {
    form.validateFields(["username","password", "phone", "email", "role_id" ])
      .then(() => {
        handleModalVisible(false)
        addOrUpdateUser()
      })
  }

  useEffect(() => {
    setForm(form)
  }, [])

  return (
    <Modal
      title="创建用户"
      visible={visible}
      onOk={modalOk}
      onCancel={handleModalVisible(false)}
    >
      <Form
        name="basic"
        form={form}
        fields={allFields}
        onFieldsChange={onFieldsChange}
        { ...layout }
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[{required: true, message: '请输入用户名!'}]}
        >
          <Input placeholder='请输入用户名'/>
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[{required: true, message: '请输入密码!'}]}
        >
          <Input.Password placeholder='请输入密码'/>
        </Form.Item>

        <Form.Item
          label="手机号"
          name="phone"
          rules={[{required: true, message: '请输入手机号!'}]}
        >
          <Input placeholder='请输入手机号'/>
        </Form.Item>

        <Form.Item
          label="邮箱"
          name="email"
          rules={[{required: true, message: '请输入邮箱!'}]}
        >
          <Input placeholder='请输入邮箱'/>
        </Form.Item>

        <Form.Item
          label="角色"
          name="role_id"
          rules={[{required: true, message: '请选择角色!'}]}
        >
          <Select>
            {
              roles.map(role => <Option key={role._id} value={role._id}>{role.name}</Option>)
            }
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default AddUpdateForm
